<template>
  <el-container direction="vertical" class="family—account"> 
    <!-- 查询面板 -->
    <QueryPanel
      v-model="queryForm"
      :fields="queryFields"
      :actions="queryActions"
      @action="handleQueryAction"
    />

    <!-- 账单列表 -->
    <DataTable
      :data="AccountList"
      :loading="loading"
      :columns="tableColumns"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
    
    <!-- 时间显示 -->
      <template #created_at="{ row }">
        <span>
          {{ formatDateTime(row.created_at) }}
        </span>
      </template>

      <!-- 账单类型：收入 / 支出 -->
      <template #type="{ row }">
        <el-tag :type="row.type === 'income' ? 'success' : 'danger'">
          {{ row.type === 'income' ? '收入' : '支出' }}
        </el-tag>
      </template>

      <!-- 金额显示（可加颜色或符号） -->
      <template #amount="{ row }">
        <span :style="{ color: row.type === 'income' ? '#07c160' : '#f56c6c' }">
          {{ row.type === 'income' ? '+' : '-' }} {{ formatAmount(row.amount) }}
        </span>
      </template>

      <!-- 操作按钮 -->
      <template #actions="{ row }">
        <el-button link type="primary" size="small" @click="handleEditAccount(row)">
          编辑
        </el-button>
        <el-button link type="danger" size="small" @click="handleDeleteAccount(row)">
          删除
        </el-button>
      </template>
    </DataTable>

    <!-- 账单表单对话框 -->
    <FormDialog
      v-model:visible="dialogVisible"
      :title="isEdit ? '编辑账单' : '添加账单'"
      :model-value="AccountForm"
      :fields="accountFormFields"
      :rules="accountFormRules"
      :loading="saving"
      @submit="saveAccount"
      @close="resetAccountForm"
    />

  </el-container>
</template>

<script setup lang="ts">
import { AccountApi, AccountInfo, AccountQuery } from '@/api/family/account';
import { reactive } from 'vue'
import QueryPanel from '@/components/query/QueryPanel.vue' 
import FormDialog from '@/components/page/FormDialog.vue'
import { useUserStore } from '@/store'

const userStore = useUserStore()
// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 查询表单
const queryForm = reactive<AccountQuery>({
  page: 1,
  pageSize: 10,
  start_datetime : getStartOfMonth(),
  end_datetime :  getToday(),
  type_ : "",
  months : 3,
})

// 查询字段配置
const queryFields = [
  {
    prop: 'start_datetime',
    label: '起始时间',
    type: 'date', // ✅ 改为日期选择器
    placeholder: '请选择开始时间'
  },
  {
    prop: 'end_datetime',
    label: '结束时间',
    type: 'date', // ✅ 改为日期选择器
    placeholder: '请选择结束时间'
  },
  {
    prop: 'type_',
    label: '类型',
    type: 'select', // ✅ 改为下拉选择
    placeholder: '请选择类型',
    options: [
      { label: '收入', value: 'income' },
      { label: '支出', value: 'expense' }
    ]
  },
  {
    prop: 'months',
    label: '过去几月',
    type: 'input', // 保留输入框，可输入数字
    placeholder: '请输入历史范围（如：3）'
  }
]

// 查询操作按钮
const queryActions = [
  { name: 'search', label: '查询', type: 'primary' as const },
  { name: 'reset', label: '重置', type: '' as const },
  { name: 'add', label: '添加账单记录', type: 'success' as const }
]

// 表格列配置
const tableColumns = [
  { prop: 'created_at', label: '记账时间',slot: 'created_at', width: 250 },
  { prop: 'type', label: '类型', slot: 'type', width: 100 },
  { prop: 'amount', label: '金额', slot: 'amount', width: 120, align: 'right' },
  { prop: 'category', label: '分类', width: 120 },
  { prop: 'remark', label: '备注', minWidth: 200 },
]

// 账单表单字段配置
const accountFormFields = [
  {
    prop: 'type',
    label: '账单类型',
    type: 'select',
    placeholder: '请选择账单类型',
    options: [
      { label: '收入', value: 'income' },
      { label: '支出', value: 'expense' }
    ],
    rules: { required: true, message: '请选择账单类型', trigger: 'change' }
  },
  {
    prop: 'amount',
    label: '金额',
    type: 'number',
    placeholder: '请输入金额',
    props: {
      precision: 2,
      step: 0.01,
      min: 0,
      controls: false
    },
    rules: { required: true, message: '请输入金额', trigger: 'blur' }
  },
  {
    prop: 'category',
    label: '分类',
    type: 'input',
    placeholder: '请输入分类',
    rules: { required: true, message: '请输入分类', trigger: 'blur' }
  },
  {
    prop: 'remark',
    label: '备注',
    type: 'textarea',
    placeholder: '请输入备注',
    props: {
      rows: 3
    }
  },
  {
    prop: 'recod_data',
    label: '记账时间',
    type: 'date',
    placeholder: '请选择记账时间',
    props: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD'
    }
  }
]

// 账单表单验证规则
const accountFormRules = {}

// 保存账单
const saveAccount = async () => {
  try {
    saving.value = true
    if (isEdit.value) {
      // 编辑模式
      await AccountApi.AccountUpdate(AccountForm)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      await AccountApi.AccountCreate(AccountForm)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadAccounts() // 刷新列表
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
  } finally {
    saving.value = false
  }
}

// 重置账单表单
const resetAccountForm = () => {
  Object.assign(AccountForm, {
    id: null,
    user_id: userStore.userInfo.id,
    family_id: 1,
    amount: 0.01,
    type: '',
    category: '',
    remark: '',
    record_date: getToday()
  })
}

// 添加账单
const handleAddAccount = () => {
  isEdit.value = false
  currentAccountId.value = null
  resetAccountForm() // 重置表单为默认值
  dialogVisible.value = true
}

// 数据状态
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentAccountId = ref<number | null>(null)
const AccountList = ref<AccountInfo[]>([])

// 查询方法
const loadAccounts = async () => {
  try {
    loading.value = true
    const response = await AccountApi.getAccountList(queryForm)
    console.log('API Response:', response) // 添加日志查看响应数据结构
    
    AccountList.value = response.data.items || []
    pagination.total = response.data.total || 0
    pagination.pageSize = response.data.page_size || pagination.pageSize
  } catch (error) {
    console.error('获取账单列表失败:', error) // 添加错误日志
    ElMessage.error('获取账单列表失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  queryForm.page = page
  loadAccounts()
}

const handleSizeChange = (size: number) => {
  queryForm.pageSize = size
  queryForm.page = 1
  loadAccounts()
}

//  格式化时间 和金额 
const formatAmount = (amount: number | string): string => {
  if (!amount) return '0.00';
  return parseFloat(String(amount)).toFixed(2);
}

// 时间格式化函数
const formatDateTime = (dateString: string): string => {
  if (!dateString) return '';
  try {
    const formatDate = new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-');
    console.log(formatDate)
    return formatDate;
  } catch (error) {
    return dateString; // 如果格式化失败，返回原始值
  }
}

const handleQueryAction = (action: string) => {
  switch (action) {
    case 'search':
      queryForm.page = 1
      loadAccounts()
      break
    case 'reset':
      Object.assign(queryForm, {
        start_datetime : getStartOfMonth(),
        end_datetime :  getToday(),
        type_ : "",
        months : 3,
        page: 1,
        pageSize: 10
      })
      loadAccounts()
      break
    case 'add':
      handleAddAccount()
      break
  }
}

// 账单表单
const AccountForm = reactive<AccountInfo>({
  id: null,
  user_id: 0,
  family_id: 1,
  amount: 0,
  type: '',
  remark: '',
  recoded_data: new Date()
})

const handleEditAccount = (account: AccountInfo) => {
  // console.log('编辑的用户ID：', userStore.userInfo.id)
  isEdit.value = true
  currentAccountId.value = account.id
  Object.assign(AccountForm, {
    id: account.id,
    user_id: userStore.userInfo.id,
    family_id: account.family_id,
    amount: account.amount,
    type: account.type,
    remark: account.remark,
    recoded_data: account.recoded_data
  })
  dialogVisible.value = true
}

const handleDeleteAccount = async (account: AccountInfo) => {
  try {
    await ElMessageBox.confirm(`确定要删除这笔${account.type === 'income' ? '收入' : '支出'}记录吗？`, '提示', {
      type: 'warning'
    })
    console.log('删除的账单ID：', account.id)  
    await AccountApi.AccountDelete(account) // 对应的API是接受对象
    ElMessage.success('删除成功')
    loadAccounts() // 重新加载账单列表
  } catch (error) { 
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
// 工具函数：获取今天（格式：YYYY-MM-DD）
function getToday() {
  return new Date().toISOString().split('T')[0]
}

// 获取本月1号（格式：YYYY-MM-DD）
function getStartOfMonth() {
  const now = new Date()
  return new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]
}

onMounted(() => {
  loadAccounts()
})
</script>